import axios from 'axios'
import io from 'socket.io-client'
//接收消息
const CHAT_REC = 'CHAT_REC'
//发送消息
const CHAT_SEND = 'CHAT_SEND'
//消息列表
const CHAT_MSG_LIST = 'CHAT_MSG_LIST'
//更新未读
const CHAT_READ = 'CHAT_READ'
let isConnect = false;
// 连接socket
const socket = io('ws://192.168.0.107:9093')
const initState = {
    userlist: [],
    chatMsgList: [],
    unRead: 0,
    isconnect: false
}

export function chatmsg(state = initState, action) {
    switch (action.type) {
        case CHAT_MSG_LIST:
            console.log(action.userid)
            return {
                ...state,
                chatMsgList: action.payload.msgs,
                userlist: action.payload.users,
                unRead: action.payload.msgs.filter(v => !v.read && action.payload.userid != v.from).length
            }
        case CHAT_REC:
            console.log(action.payload)
            // 如果发送方不是我且接收方是我则未读+1
            return {...state, chatMsgList: [...state.chatMsgList, action.payload], isconnect: true}
        default:
            return state
    }
}

function charMsgList(msgs, users, userid = "") {
    return {type: CHAT_MSG_LIST, payload: {msgs, users, userid}}
}

function AddReceveMsg(msg) {
    return {type: CHAT_REC, payload: msg}
}

// 修改未读状态
function ChangeReadState(from, userid, num) {
    return {type: CHAT_READ, payload: {from, userid, num}}
}

// 获取消息列表
export function getChatMsgList() {
    return (dispatch, getState) => {

        axios.get(`/user/getmsgList`)
            .then(res => {
                console.log(res.data)
                if (res.data.code == 0) {
                    console.log(getState().user._id)
                    dispatch(charMsgList(res.data.msgs, res.data.users, getState().user._id))
                }
            })
    }
}

export function ReceveMsg() {
    if(!isConnect){
        console.log("我连接");
        isConnect = true;
        return (dispatch) => {
            socket.on("recvmsg", (obj) => {
                dispatch(AddReceveMsg(obj))
            })
        }
    }else{
        console.log("我在这");
        return (dispatch)=>{

        }
    }
}
//发送消息
export function SendMsg(msg) {
    return dispatch => {
        console.log("msg",msg);
        socket.emit("sendmsg", msg)
    }
}

//更新未读消息
export function setRead(from) {
    return (dispatch, getState) => {
        axios.post("/user/setRead", {from}).then(res => {
            if (res.data.code == 0) {
                dispatch(ChangeReadState(from, getState().user._id, res.data.num))
            }
        })
    }
}
